package com.translator.ui;

import com.translator.config.AppConfig;
import com.translator.engine.TranslationEngine;
import com.translator.engine.TranslationEngineFactory;
import com.translator.model.Language;
import com.translator.model.TranslationRequest;
import com.translator.model.TranslationResult;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Objects;

/**
 * 翻译软件主界面
 * 提供用户交互界面，包括文本输入、翻译引擎选择、语言选择等功能
 */
public class MainFrame extends JFrame {

    private JTextArea sourceTextArea;
    private JTextArea resultTextArea;
    private JComboBox<String> sourceLanguageComboBox;
    private JComboBox<String> targetLanguageComboBox;
    private JComboBox<String> engineComboBox;
    private JButton translateButton;
    private JButton settingsButton;
    private JButton swapLanguageButton;
    private TranslationEngine currentEngine;
    private StatusBar statusBar;
    
    public MainFrame() {
        initComponents();
        setupLayout();
        setupListeners();
        loadConfiguration();
        setTitle("多功能翻译软件");
        setSize(800, 600);
        setMinimumSize(new Dimension(850, 600));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void initComponents() {
        // 初始化文本区域
        sourceTextArea = new JTextArea();
        sourceTextArea.setLineWrap(true);
        sourceTextArea.setWrapStyleWord(true);
        sourceTextArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14));
        
        resultTextArea = new JTextArea();
        resultTextArea.setLineWrap(true);
        resultTextArea.setWrapStyleWord(true);
        resultTextArea.setEditable(false);
        resultTextArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14));
        
        // 初始化下拉框
        sourceLanguageComboBox = new JComboBox<>();
        sourceLanguageComboBox.setPreferredSize(new Dimension(100, 28));
        
        targetLanguageComboBox = new JComboBox<>();
        targetLanguageComboBox.setPreferredSize(new Dimension(100, 28));
        
        engineComboBox = new JComboBox<>();
        engineComboBox.setPreferredSize(new Dimension(100, 28));
        
        // 初始化按钮
        translateButton = new JButton("翻译");
        translateButton.setPreferredSize(new Dimension(100, 28));
        translateButton.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/icons/translate.png"))));
        
        settingsButton = new JButton("设置");
        settingsButton.setPreferredSize(new Dimension(100, 28));
        settingsButton.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/icons/settings.png"))));
        
        swapLanguageButton = new JButton("");
        swapLanguageButton.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource("/icons/swap.png"))));
        swapLanguageButton.setPreferredSize(new Dimension(28, 28));
        swapLanguageButton.setToolTipText("交换语言");
        
        // 初始化状态栏
        statusBar = new StatusBar();
    }
    
    private void setupLayout() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
        
        // 创建顶部控制面板
        JPanel controlPanel = new JPanel(new BorderLayout(5, 0));
        
        // 创建语言选择面板
        JPanel languagePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
//        languagePanel.add(new JLabel("源语言:"));
        languagePanel.add(sourceLanguageComboBox);
        languagePanel.add(swapLanguageButton);
//        languagePanel.add(new JLabel("目标语言:"));
        languagePanel.add(targetLanguageComboBox);
        
        // 创建引擎选择面板
        JPanel enginePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
        enginePanel.add(new JLabel("翻译引擎:"));
        enginePanel.add(engineComboBox);
        enginePanel.add(translateButton);
        enginePanel.add(settingsButton);
        
        // 将语言面板和引擎面板添加到控制面板
        controlPanel.add(languagePanel, BorderLayout.WEST);
        controlPanel.add(enginePanel, BorderLayout.EAST);
        
        // 创建文本区域面板
        JPanel textPanel = new JPanel(new GridLayout(1, 2, 10, 0));
        
        // 创建源文本面板
        JPanel sourcePanel = new JPanel(new BorderLayout(0, 5));
        sourcePanel.add(new JLabel("输入文本:"), BorderLayout.NORTH);
        sourcePanel.add(new JScrollPane(sourceTextArea), BorderLayout.CENTER);
        
        // 创建结果文本面板
        JPanel resultPanel = new JPanel(new BorderLayout(0, 5));
        resultPanel.add(new JLabel("翻译结果:"), BorderLayout.NORTH);
        resultPanel.add(new JScrollPane(resultTextArea), BorderLayout.CENTER);
        
        // 添加源文本和结果文本面板到文本面板
        textPanel.add(sourcePanel);
        textPanel.add(resultPanel);
        
        // 添加到主面板
        mainPanel.add(controlPanel, BorderLayout.NORTH);
        mainPanel.add(textPanel, BorderLayout.CENTER);
        mainPanel.add(statusBar, BorderLayout.SOUTH);
        
        // 设置内容面板
        setContentPane(mainPanel);
    }
    
    private void setupListeners() {
        // 翻译按钮监听器
        translateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performTranslation();
            }
        });
        
        // 设置按钮监听器
        settingsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openSettingsDialog();
            }
        });
        
        // 引擎选择监听器
        engineComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateCurrentEngine();
            }
        });
        
        // 语言交换按钮监听器
        swapLanguageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                swapLanguages();
            }
        });
        
        // 添加键盘快捷键
        KeyStroke translateKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK);
        translateButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(translateKeyStroke, "translate");
        translateButton.getActionMap().put("translate", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performTranslation();
            }
        });
    }
    
    private void loadConfiguration() {
        // 加载语言选项
        List<Language> languages = Language.getAllLanguages();
        for (Language language : languages) {
            sourceLanguageComboBox.addItem(language.getName());
            targetLanguageComboBox.addItem(language.getName());
        }
        
        // 设置默认语言（中文 -> 英文）
        sourceLanguageComboBox.setSelectedItem("中文");
        targetLanguageComboBox.setSelectedItem("英文");
        
        // 暂时移除引擎选择监听器，防止加载引擎列表时触发事件
        ActionListener[] listeners = engineComboBox.getActionListeners();
        for (ActionListener listener : listeners) {
            engineComboBox.removeActionListener(listener);
        }
        
        // 加载翻译引擎选项
        List<String> engineNames = TranslationEngineFactory.getAvailableEngineNames();
        for (String engineName : engineNames) {
            engineComboBox.addItem(engineName);
        }
        
        // 设置默认引擎
        String defaultEngine = AppConfig.getInstance().getDefaultEngine();
        if (defaultEngine != null && !defaultEngine.isEmpty()) {
            engineComboBox.setSelectedItem(defaultEngine);
        }
        
        // 重新添加引擎选择监听器
        for (ActionListener listener : listeners) {
            engineComboBox.addActionListener(listener);
        }
        
        // 初始化当前引擎
        updateCurrentEngine();
    }
    
    private void updateCurrentEngine() {
        String selectedEngineName = (String) engineComboBox.getSelectedItem();
        currentEngine = TranslationEngineFactory.createEngine(selectedEngineName);
        
        // 保存当前选择的引擎作为默认引擎，以便下次启动时使用
        AppConfig.getInstance().setDefaultEngine(selectedEngineName);
        AppConfig.getInstance().saveConfig();
    }
    
    private void performTranslation() {
        if (currentEngine == null) {
            JOptionPane.showMessageDialog(this, "请选择翻译引擎", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        String sourceText = sourceTextArea.getText();
        if (sourceText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入要翻译的文本", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        String sourceLanguage = (String) sourceLanguageComboBox.getSelectedItem();
        String targetLanguage = (String) targetLanguageComboBox.getSelectedItem();
        
        TranslationRequest request = new TranslationRequest(sourceText, sourceLanguage, targetLanguage);
        
        try {
            // 更新状态栏
            statusBar.setStatus("正在翻译...");
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            translateButton.setEnabled(false);
            
            // 记录开始时间
            long startTime = System.currentTimeMillis();
            
            // 执行翻译
            TranslationResult result = currentEngine.translate(request);
            resultTextArea.setText(result.getTranslatedText());
            
            // 计算耗时并更新状态栏
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            statusBar.setStatus(String.format("翻译完成，耗时 %.2f 秒", duration / 1000.0));
            
        } catch (Exception ex) {
            statusBar.setStatus("翻译失败: " + ex.getMessage());
            JOptionPane.showMessageDialog(this, "翻译失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            setCursor(Cursor.getDefaultCursor());
            translateButton.setEnabled(true);
        }
    }
    
    private void openSettingsDialog() {
        SettingsDialog settingsDialog = new SettingsDialog(this);
        settingsDialog.setVisible(true);
        
        // 如果设置已更改，重新加载配置
        if (settingsDialog.isConfigChanged()) {
            updateCurrentEngine();
            statusBar.updateProxyStatus();
        }
    }
    
    /**
     * 交换源语言和目标语言
     */
    private void swapLanguages() {
        Object sourceLanguage = sourceLanguageComboBox.getSelectedItem();
        Object targetLanguage = targetLanguageComboBox.getSelectedItem();
        
        sourceLanguageComboBox.setSelectedItem(targetLanguage);
        targetLanguageComboBox.setSelectedItem(sourceLanguage);
        
        // 如果已有翻译结果，则交换源文本和结果文本
        String resultText = resultTextArea.getText();
        if (resultText != null && !resultText.isEmpty()) {
            String sourceText = sourceTextArea.getText();
            sourceTextArea.setText(resultText);
            resultTextArea.setText("");
            statusBar.setStatus("语言已交换，可以重新翻译");
        }
    }
}